﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using VH.SharePoint.Api.Helpers;

namespace VH.SharePoint.Api.Entensions
{
    public static class SPWebExtensions
    {
        public static void SetProperty<T>(this SPWeb web, string key, T value)
        {
            object v = value;
            Type vType = value.GetType();
            if (vType != typeof (Int32) && vType != typeof (DateTime) && vType != typeof (String))
            {
                v = JsonHelper.JsonSerializer(value);
            }
            if (web.AllProperties.ContainsKey(key))
                web.AllProperties[key] = v;
            else
            {
                web.AllProperties.Add(key, v);
            }
        }

        public static T GetProperty<T>(this SPWeb web, string key, T defaultValue)
        {
            var value = GetProperty<T>(web, key);
            return Equals(value, default(T)) ? defaultValue : value;
        }

        public static T GetProperty<T>(this SPWeb web, string key)
        {
            try
            {
                if (web.AllProperties.ContainsKey(key))
                {
                    var tType = typeof (T);
                    if(tType == typeof (Int32) || tType == typeof (DateTime) || tType == typeof (String))
                     return (T) Convert.ChangeType(web.AllProperties[key], typeof (T));
                    return JsonHelper.JsonDeserialize<T>(web.AllProperties[key].ToString());
                }
            }
            catch (Exception exception)
            {
                
            }
            
            return default(T);
        }
    }
}
